const { toUrl,globalData,msgLoading } = getApp();
import { request } from "@/utils/request";
Page({
  toUrl,
  data: {
    globalData,
    typeObj: null,
    detail: null,
    coupons: null,
    orderSn: null,
    pageNum: 0,
    isPay: false,
    isBack: false,
    loading:true,
    quota_num:0
  },
  getPageNum(num) {
    const page = getCurrentPages()
    if(page.length > 2) {
      const len = page.length - 1 - num
      if( page[len].route == 'pages/order/form' ) {
        // console.log('+1')
        this.setData({
          pageNum: this.data.pageNum + 1
        })
        this.getPageNum(num+1)
      }
    }else {
      this.setData({
        pageNum: 1
      })
    }
    console.log(this.data.pageNum)
  },
  goback() {
    // const page = getCurrentPages()
    //   let pageNum = 0
    //   let isPlus = true
    //   for(let i = page.length-1; i > 0; --i) {
    //     if(page[i].route == 'pages/order/form') {
    //       if(isPlus) {
    //         pageNum++
    //       }
    //     }else {
    //       isPlus = false
    //     }
    //   }
    //   console.log(pageNum)
    //   this.setData({
    //     isBack: true
    //   })
    //   wx.navigateBack({
    //     delta: pageNum
    //   })

    wx.navigateBack({
      delta: 1,
    })


    // wx.navigateTo({
    //   url: '/pages/store/detail?suppliers_id='+this.data.detail.store.suppliers_id,
    // })
  },
  //增加商品数量
  plus(e) {
    // console.log(this.detail);
    let numr77 = this.data.detail.goods[0]?.num
    if (this.data.quota_num == numr77) {
      wx.showToast({
        title: `限购${this.data.quota_num}个`,
        icon:'none'
      })
      return
    }

    if (this.data.detail.info.is_voucher == 1) {
      wx.showToast({
        title: '该商品属于优惠券商品,数量限购一个',
        icon:'none'
      })
      return
    }
    const type = this.data.typeObj.type;
    const goods = this.data.detail.goods;
    const index = e.currentTarget.dataset.index;
    const ids = goods[index].id;
    const num = goods[index].num;
    //更新购物车数量
    if (type == "cart") {
      const data = {
        typeid: 1,
        ids: ids,
        num: num + 1,
      };
      request("cart/setcart", { data }).then((res) => {
        if (res.errcode == 1) {
          this.getCartOrder();
        }
      });
    }
    if (type == "buy") {
      const typeObj = this.data.typeObj;
      typeObj.num = Number(typeObj.num) + 1;
      this.setData({
        typeObj: typeObj,
      });
      this.getBuyOrder();
    }
  },
  //减少商品数量
  del(e) {
    const goods = this.data.detail.goods;
    const index = e.currentTarget.dataset.index;
    const num = goods[index].num;
    if (num == 1) {
      return;
    }
    const type = this.data.typeObj.type;
    const ids = goods[index].id;
    //更新购物车数量
    if (type == "cart") {
      const data = {
        typeid: 1,
        ids: ids,
        num: num - 1,
      };
      request("cart/setcart", { data }).then((res) => {
        if (res.errcode == 1) {
          this.getCartOrder();
        }
      });
    }
    if (type == "buy") {
      const typeObj = this.data.typeObj;
      if (typeObj.num == 1) {
        return;
      }
      typeObj.num = Number(typeObj.num) - 1;
      this.setData({
        typeObj: typeObj,
      });
      this.getBuyOrder();
    }
  },
  //获取购物车订单
  getCartOrder() {
    const that = this;
    const data = {
      typeid: 2,
      coupon_id: this.data.coupons ? this.data.coupons.coupon_id : 0,
      ids: this.data.typeObj.ids,
      suppliers_id: this.data.typeObj.suppliers_id,
    };
    return request("cart/addorder", { data }).then((res) => {
      const list = res.data
      const {goods} = list
      goods.forEach(item => {
        item.image = globalData.baseUrl + item.image
      })
      that.setData({
        detail: list,
        loading:false
      });
    }).finally(()=>{
      wx.hideLoading()
    })
  },
  //获取直接购买订单
  getBuyOrder() {
    const that = this;
    const data = {
      typeid: 1,
      coupon_id: this.data.coupons ? this.data.coupons.coupon_id : 0,
      goods_id: this.data.typeObj.goods_id,
      num: this.data.typeObj.num,
    };
    if (this.data.typeObj.item_id) {
      data.item_id = this.data.typeObj.item_id;
    }
    return request("cart/addorder", { data }).then((res) => {
      const list = res.data
      const {goods} = list
      goods.forEach(item => {
        item.image = globalData.baseUrl + item.image
      })
      that.setData({
        detail: list,
        loading:false

      });
    }).finally(()=>{
      wx.hideLoading()
    })
  },
  //获取优惠券页面
  getTicket() {
    wx.redirectTo({
      url:
        "/pages/order/ticket/ticket?obj=" + JSON.stringify(this.data.typeObj),
    });
  },
  //提交订单
  submit() {
    const that = this
    const data = {
      // typeid: this.data.typeObj.type == "cart" ? 2 : 1,
      coupon_id: this.data.coupons ? this.data.coupons.coupon_id : 0,
      act: "submit",
    };
    let url = 'cart/addorder'
    //购物车提交订单提交数据
    if (this.data.typeObj.type == "cart") {
      data.typeid=2,
      data.ids = this.data.typeObj.ids;
      data.suppliers_id = this.data.typeObj.suppliers_id;
    }
    //直接购买订单提交数据
    if (this.data.typeObj.type == "buy") {
      data.typeid=1,
      data.goods_id = this.data.typeObj.goods_id;
      data.item_id = this.data.typeObj.item_id;
      data.num = this.data.typeObj.num;
    }

     //复购订单提交数据
     if (this.data.typeObj.type == "repurchase") {
      url='cart/againorder',
      data.order_id = this.data.typeObj.order_id;
    }
    request(url, { data }).then((res) => {
      const { order_sn } = res.data;
      that.setData({
        orderSn: order_sn
      })
      const data = {
        order_sn: order_sn,
      };
      if(res.data.pay_status == 1) {
        wx.showToast({
          title: res.message,
        })
        that.setData({
          isPay: true
        })
        wx.redirectTo({
          url: './status/status?order_sn='+res.data.order_sn,
        })
      }else {
        wx.showLoading({
          title: '加载中...',
          icon:'none',
          mask:true,
        })
        request("payment/pay", { data }).then((res) => {
          wx.requestPayment({
            appId: res.data.appId,
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            package: res.data.package,
            signType: res.data.signType,
            paySign: res.data.paySign,
            success: function (res) {
              console.log(res);
              if(res.errMsg == 'requestPayment:ok') {
                that.setData({
                  isPay: true
                })
                wx.redirectTo({
                  url: './status/status?order_sn='+that.data.orderSn,
                })
              }
              wx.hideLoading()

            },fail:function(res){
              that.getCancel()
              wx.hideLoading()

            }
          });
        });
      }
      
    });
  },
  getCancel(){
    let data = {
      order_sn:this.data.orderSn
    }
    return request("order/cancel", {
      data
    }).then((res) => {
      console.log('取消成功');
      // this.setData({
      //   detail: res.data,
      // });
    });
  },
  getRepurchase(order_id) {
    let data = {
      order_id: this.data.typeObj.order_id,
      coupon_id: this.data.coupons ? this.data.coupons.coupon_id : 0,
    };
    return  request("cart/againorder", { data }).then((res) => {
      this.setData({
        detail: res.data,
        loading:false
      });
    }).finally(()=>{
      wx.hideLoading()
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    msgLoading()
    console.log(options);
    this.setData({
      quota_num:options.quota_num
    })
    if (options.type === "cart") {
      this.setData({
        typeObj: options,
      });
      //获取购物车
      this.getCartOrder().then(() => {
        if (options.coupons_id) {
          const obj = this.data.detail.coupons.find((item) => {
            return item.coupon_id == options.coupons_id;
          });
          this.setData({
            coupons: obj,
          });
          this.getCartOrder();
        }
      });
    }
    if (options.type === "buy") {
      this.setData({
        typeObj: options,
      });
      this.getBuyOrder().then(() => {
        if (options.coupons_id) {
          const obj = this.data.detail.coupons.find((item) => {
            return item.coupon_id == options.coupons_id;
          });
          this.setData({
            coupons: obj,
          });
          this.getBuyOrder();
        }
      });
    }
    if (options.type === "repurchase") {
      this.setData({
        typeObj: options,
      });
      //再来一单
      this.getRepurchase().then(() => {
        if (options.coupons_id) {
          const obj = this.data.detail.coupons.find((item) => {
            return item.coupon_id == options.coupons_id;
          });
          this.setData({
            coupons: obj,
          });
          this.getRepurchase();
        }
      });

      // let { order_id } = options;
      // this.getRepurchase(order_id);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const page = getCurrentPages()
        console.log(page)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if(this.data.isPay) {
      wx.redirectTo({
        url: './status/status?order_sn='+this.data.orderSn,
      })
    }
    // else if(!this.data.isBack) {
    //   const page = getCurrentPages()
    //   let pageNum = 0
    //   let isPlus = true
    //   for(let i = page.length-1; i > 0; --i) {
    //     if(page[i].route == 'pages/order/form') {
    //       if(isPlus) {
    //         pageNum++
    //       }
    //     }else {
    //       isPlus = false
    //     }
    //   }
    //   wx.navigateBack((pageNum - 1))
    // }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
